package com.gopay.scheduler.shedulerx.util;

import com.alibaba.dubbo.common.utils.NetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.util.Set;

/**
 * @author 19371
 */
public class NetAddressUtils {
    /**
     * eg :  <Connector port="8080" redirectPort="8443" connectionTimeout="20000" protocol="HTTP/1.1"/>
     */
    public static String url(){
        int tomcatPort = 0;
        Set<ObjectName> objectNames = null;
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        String port = objectNames.iterator().next().getKeyProperty("port");
         tomcatPort = Integer.valueOf(port);
        } catch (MalformedObjectNameException e) {
           LOGGER.error("---------->scheduler fetch the url fail<----------",e);
        }
        return String.format("%s:%s",NetUtils.getLocalHost(),tomcatPort);
    }
     private final static Logger LOGGER = LoggerFactory.getLogger(NetAddressUtils.class);
}
